var express = require('express');
// 导入moment
const moment = require('moment')
const AccountModel = require('../../models/AccountModel')
const checkTokenMiddleware = require('../../middlewares/checkTokenMiddleware')

var router = express.Router();

// 获取账单明细
router.get('/account', checkTokenMiddleware, (req, res, next) => {
  // console.log(req.user, '8888');
    AccountModel.find().sort({ time: -1 }).then(data => {
      // console.log(data);
      res.json({
        code: '0000',
        msg: '获取成功',
        data: data
      })
    }).catch(err => {
      res.json({
        code: '1001',
        msg: '获取失败',
        data: null
      })
    })
  


})

// 提交账单
router.post('/account',checkTokenMiddleware, (req, res, next) => {
  console.log(req.body);
  AccountModel.create({
    ...req.body,
    time: moment(req.body.time).toDate()
  }).then(data => {
    res.json({
      code: '0000',
      msg: '添加成功',
      data: data
    })
  }).catch(err => {
    res.json({
      code: '1002',
      msg: '添加失败',
      data: null
    })
  })

})

// 删除账单
router.delete('/account/:id',checkTokenMiddleware, (req, res, next) => {
  console.log(req.params.id);
  AccountModel.deleteOne({ _id: req.params.id }).then(data => {
    res.json({
      code: '0000',
      msg: '删除成功',
      data: data
    })
  }).catch(err => {
    res.json({
      code: '1003',
      msg: '删除失败',
      data: null
    })
  })
})

// 获取单个账单信息
router.get('/account/:id',checkTokenMiddleware, (req, res, next) => {
  AccountModel.findById(req.params.id).then(data => {
    res.json({
      code: '0000',
      msg: '获取成功',
      data: data
    })
  }).catch(err => {
    res.json({
      code: '1004',
      msg: '获取失败',
      data: null
    })
  })
})

// 更新单个账单信息
router.patch('/account/:id',checkTokenMiddleware, (req, res, next) => {
  console.log(req.body);
  AccountModel.updateOne({ _id: req.params.id }, req.body).then(data => {
    AccountModel.findById(req.params.id).then(data => {
      res.json({
        code: '0000',
        msg: '更新成功',
        data: data
      })
    }).catch(err => {
      res.json({
        code: '1004',
        msg: '获取失败',
        data: null
      })
    })
  }).catch(err => {
    res.json({
      code: '1005',
      msg: '更新失败',
      data: null
    })
  })
})

module.exports = router;
